/*
 * Download.java
 * 
 * This file is part of Netuno Proteu.
 * 
 * CajuScript is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3, or (at your option) 
 * any later version.
 * 
 * CajuScript is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with CajuScript.  If not, see <http://www.gnu.org/licenses/>.
*/

package org.netuno.proteu;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.log4j.Logger;

/**
 * Download files.
 * @author eduveks
 */
public class Download {
    static Logger logger = Logger.getLogger(Download.class);
    /**
     * Send bytes of a file for the client.
     * @param proteu Proteu
     * @param file Path of file to send for the client
     */
    public Download(Proteu proteu, File file) {
        FileInputStream fis = null;
        try {
            if (file.exists()) {
            	proteu.getResponseHead().set("Last-Modified", Http.getDateGTM(new java.util.Date(file.lastModified())));
                proteu.getResponseHead().set("Cache-Control", "cache");
                if (!proteu.getRequestHead().getString("If-Modified-Since").equals("")) {
                    if (proteu.getRequestHead().getString("If-Modified-Since").indexOf(Http.getDateGTM(new java.util.Date(file.lastModified()))) > -1) {
                        proteu.getResponseHead().set("HTTP", "HTTP/1.0 304 Not Modified");
                        proteu.start();
                        return;
                    }
                }
                if (file.toString().lastIndexOf(".") < file.toString().length() - 1) {
                    proteu.getResponseHead().set("Content-Type", Config.getMimeTypes().search(file.toString().substring(file.toString().lastIndexOf(".") + 1), ","));
                }
                fis = new FileInputStream(file);
                proteu.getResponseHead().set("Content-Length", "" + fis.available());
                int startIn = 0;
                proteu.getResponseHead().set("Content-Range", startIn +"-"+ (file.length()-1) +"/"+ file.length());
                startIn = proteu.getRequestHead().getInt("Range");
                if (startIn > 0) {
                    fis.skip(startIn);
                }
                Download.sendInputStream(proteu, fis);
                logger.warn("Downloaded "+ file.toString() +" "+  proteu.getResponseHead().getString("Content-Length") +" bytes");
            } else {
            	logger.warn("Not found... "+ file.toString());
                new Error404(proteu);
            }
        } catch (Exception e) {
            logger.warn("Download: "+ file.toString(), e);
            throw new Error(e);
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch(Exception e) {
                throw new Error(e);
            } finally {
                fis = null;
                proteu = null;
                file = null;
            }
        }
    }

    /**
     * Send a InputStream.
     * @param proteu Proteu
     * @param in InputStream to send
     */
    public static synchronized void sendInputStream(Proteu proteu, InputStream in) throws IOException {
        byte[] buffer;
        try {
            while(true) {
                buffer = new byte[Config.getBufferSize()];
                synchronized (buffer) {
                    int amountRead = in.read(buffer, 0, Config.getBufferSize());
                    if (amountRead <= 0) {
                        break;
                    }
                    proteu.getOutput().write(buffer, 0, amountRead);
                }
                buffer = null;
            }
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                throw e;
            } finally {
                buffer = null;
                in = null;
            }
        }
    }
}
